<template>
  <div>
    <div id="gantt_here" style="height: calc(100vh - 180px);"></div>
    <div v-show="contextMenuVisible">
      <ul :style="{left:left+'px',top:top+'px'}" class="contextmenu">
        <li><el-button type="text" size="mini" @click="rightMenuOpear().switchTask()">切换分组</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().modifyTask()" v-if="modifyTaskShow">修改任务</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().addChildTask()" v-if="addChildTaskShow">添加子任务</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().editTask()" v-if="editTaskShow">编辑任务</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().editMilestone()" v-if="editMilestoneShow">编辑里程碑</el-button></li>
        <el-divider class="divider"/>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().startTask()" v-if="startTask" :disabled="!startTask">开始任务</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().hangUp()" v-if="hangUpTaskShow" :disabled="!hangUpTaskShow">挂起任务</el-button></li>
        <li><el-button type="text" size="mini" @click="rightMenuOpear().endTask()" v-if="endTaskShow" :disabled="!endTaskShow">结束任务</el-button></li>
      </ul>
    </div>
  </div>
</template>

<script>
import { gantt } from 'dhtmlx-gantt'
import * as format from "@/filters";
import projectTaskApi from "@/api/projectTaskApi";
import taskEditApi from './taskEditApi.js'
import { hanlderGroup } from './gttComponent_hanlder'

export default {
  mixins: [taskEditApi],
  name: "gttComponent",
  props: {
    planData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      modifyTaskShow: false,
      editTaskShow: false,
      hangUpTaskShow: false,
      startTask: false,
      endTaskShow: false,
      editMilestoneShow: false,
      addChildTaskShow: false,

      taskStatus: ['未开始', '进行中', '已完成', '已暂停', '已取消', '已关闭'],
      contextMenuVisible: false,
      isInitGtt: false,
      linkUpdateThrottle: undefined,
      TaskDragThrottle: undefined,
      rightMenuThrottle: undefined,
      tableData: [],
      left: 0,
      rightMenuOpearTaskId: '',
      top: 0,
      isFrist: false
    }
  },
  methods: {
    yjOpenClose () {
      let that = this
      gantt.eachTask(function(task){
        task.$open = !task.$open;
      });
      gantt.render();
    },
    // 全屏模式
    fullscreen () {
      gantt.expand();
    },

    // 数组转树
    arrayToTree (data) {
      let test = []
      let p = data.filter(it1 => it1.Parenttaskid === '0') || []
      p.forEach(it => {
        let child = data.filter(it1 => it1.Parenttaskid === it.Id)
        it.children = child || []
        it.children.forEach(it1 => {
          let child1 = data.filter(it2 => it2.Parenttaskid === it1.Id)
          it1.children = child1 || []
          it1.children.forEach(it2 => {
            let child2 = data.filter(it3 => it3.Parenttaskid === it2.Id)
            it2.children = child2 || []
            it2.children.forEach(it3 => {
              let child3 = data.filter(it4 => it4.Parenttaskid === it3.Id)
              it3.children = child3 || []
            })
          })
        })
      })
      p.sort((a, b) => a.Orders - b.Orders)
      p.forEach(it => {
        test.push(it)
        if (it.children.length > 0) {
          it.children.sort((a, b) => a.Orders - b.Orders)
          it.children.forEach(it1 => {
            test.push(it1)
            if (it1.children.length > 0) {
              it1.children.sort((a, b) => a.Orders - b.Orders)
              it1.children.forEach(it1 => {
                test.push(it1)
                if (it1.children.length > 0) {
                  it1.children.sort((a, b) => a.Orders - b.Orders)
                  it1.children.forEach(it1 => {
                    test.push(it1)
                    if (it1.children.length > 0) {
                      it1.children.sort((a, b) => a.Orders - b.Orders)
                      it1.children.forEach(it1 => {
                        test.push(it1)
                      })
                    }
                  })
                }
              })
            }
          })
        }
      })
      return test
    },
    showTaskLists (data) {
      gantt.clearAll()
      this.tableData = JSON.parse(JSON.stringify(data))
      this.tableData = this.arrayToTree(this.tableData)
      this.initGantt()
      this.tableData.forEach((it, index) => {
        it.resourcesStoreId = it.Id// `${it.Acceptid}${index}`
      })

      this.$nextTick(_ => {
        let a = []
        // let a_1 = []
        let b = this.tableData //this.flatArray(data, [])
        // gantt.clearAll();
        let links = []
        b.forEach((it, index) => {
          let Ended = it.Ended
          if (Ended.toString().length !== 13) Ended = Ended * 1000
          let s = it.Started.toString().length === 13 ? it.Started : it.Started * 1000
          if (format.formatDatetime(s, 'yyyy-MM-dd') === format.formatDatetime(Ended, 'yyyy-MM-dd')) {
            Ended = Ended + (86400 * 1000)
          } else {
            Ended = Ended + (86400 * 1000)
          }
          let e = Ended
          let aw = format.formatDatetime(s, 'yyyy-MM-dd') + ' 00:00'
          let ended = format.formatDatetime(e, 'yyyy-MM-dd') + ' 00:00'
          let wd1 = parseInt(((new Date(ended).valueOf() - new Date(aw).valueOf()) / (1000 * 60 * 60 * 24)).toString())
          let a1 = {
            id: it.Id,
            text: it.Name,
            user_id: [{
              resource_id: it.resourcesStoreId,
              value: 8
            }],
            start_date: aw,
            progress: (it.Progress / 100),
            parent: it.Parenttaskid,
            duration: it.Parenttaskid === '0' ? null : wd1,
            Userrealname: it.Userrealname,
            status: it.Status,
            value: it.Parenttaskid === '0' ? null : wd1,
            deadline: new Date(ended),
            type: this.gttType(it, b, index),
            lEndDate: ended,
            index: it.Orders,
            remoteOrder: it.Orders
          }
          // if (it.Tasktimes) {
          //   it.Tasktimes.forEach(it => {
          //
          //   })
          // }
          a.push(a1);
          it.Related = it.Related || []
          it.Related.forEach(it1 => {
            links.push({
              id: it1.Id,
              source: it1.taskid,
              target: it1.Related,
              type: it1.Directionbefore.toString()//gantt.config.links.finish_to_start
            })
          })
        })
        a.forEach(it => {
          if (it.parent === '0') {
            it.project_start = new Date(it.start_date)
            it.project_end = new Date(it.lEndDate)
          }
        })
        gantt.$resourcesStore.parse(hanlderGroup(this.tableData).w1);
        if (a.length === 0) {
          gantt.clearAll()
        } else {
          gantt.parse({
            data: a,
            links: links
          });
        }
      })
    },
    // 更新排序

    initGantt () {
      let that = this
      let diff = 0;
      that.$nextTick(_ => {
        gantt.plugins({
          auto_scheduling: true
        });
        gantt.i18n.setLocale("cn");
        gantt.config.date_format = "%Y-%m-%d %H:%i";
        // gantt.config.autoscroll = true
        // gantt.config.initial_scroll = true
        // gantt.config.autosize = "xy";
        gantt.config.autofit = true;
        gantt.config.grid_width = 600

        gantt.config.resource_store = "users";
        gantt.config.auto_scheduling = true;
        gantt.config.resource_property = "user_id";
        gantt.config.order_branch = 'marker';
        gantt.config.order_branch_free = true;

        // 提示框
        // gantt.plugins({
        //   tooltip: true
        // });
        // gantt.attachEvent("onGanttReady", function () {
        //   let tooltips = gantt.ext.tooltips;
        //   tooltips.tooltipFor({
        //     selector: ".gantt_resource_marker",
        //     html: function (event, node) {
        //       console.log(event, node)
        //       return '<div>3123123</div>'
        //     }
        //   })
        // })
        gantt.templates.tooltip_text = function(start,end,task){
          var overdue = Math.ceil(((new Date().getTime() - end.getTime()) / (24 * 60 * 60 * 1000)));
          let a = '';
          let start_end = ''
          let progress = ''
          if (task.type !== 'milestone') {
            if (overdue > 1 && task.progress !== 1) {
              a += ("<br/><b style='color: red'>已延期:</b><b style='color: red'>" + overdue + " 天</b>")
            }
            let s = format.formatDatetime(task.start_date.valueOf(), 'yyyy-MM-dd')
            let e = format.formatDatetime(task.end_date.valueOf(), 'yyyy-MM-dd')
            start_end = "<br/><b>开始时间: " + s + " </b>" + "<br/><b>结束时间: " + e + " </b>"
            progress = "<br/><b> 进度:</b> "+ Math.ceil(task.progress * 100) + '%'
          } else {
            let s = format.formatDatetime(task.start_date.valueOf(), 'yyyy-MM-dd')
            start_end = "<br/><b>开始时间: " + s + " </b>"
          }
          return "<b>指派人:</b> "+ task.Userrealname +
              "<br/><b>任务名称:</b> "+ task.text +
              "<br/><b>持续时间:</b> " + task.duration +
              start_end +
              progress +
              a;
        };
        gantt.templates.rightside_text = function(start, end, task){
          return "ID: #" + task.id;
        };
        gantt.templates.task_text=function(start,end,task){
          // return "<b>标题:</b> "+task.text+",<b> 进度:</b> "+ Math.ceil(task.progress * 100) + '%';
          return "<b> 进度:</b> "+ Math.ceil(task.progress * 100) + '%';
        };
        gantt.templates.scale_cell_class = function(date){
          if(date.getDay() === 0 || date.getDay() === 6){
            return "weekend";
          }
        };
        gantt.templates.timeline_cell_class = function(task,date){
          if(date.getDay() === 0 || date.getDay() === 6){
            return "weekend" ;
          }
        };
        // 状态线
        gantt.plugins({
          marker: true
        });
        // var dateToStr = gantt.date.date_to_str(gantt.config.task_date);
        let markerId1 = gantt.addMarker({
          start_date: new Date(),
          css: "today",
          text: "今天",
          title: format.formatDatetime(new Date().getTime())
        });
        setInterval(function(){
          let today = gantt.getMarker(markerId1);
          if (today) {
            today.start_date = new Date();
            today.title = format.formatDatetime(new Date().getTime());
            gantt.updateMarker(markerId1);
          }
        }, 1000*60);
        let a = this.planData.Started.toString().length === 13 ? this.planData.Started : this.planData.Started * 1000
        let markerId2 = gantt.addMarker({
          start_date: new Date(a),
          css: "planStartTime",
          text: "计划开始时间",
          title: format.formatDatetime(a)
        });
        let getResourceAssignments = (resourceId) => {
          let assignments;
          let store = gantt.getDatastore(gantt.config.resource_store);
          let resource = store.getItem(resourceId);

          if(resource.hasOwnProperty('taskId')){
            assignments = gantt.getResourceAssignments(resource.id, resource.taskId);
          }else{
            assignments = gantt.getResourceAssignments(resourceId);
            if(store.eachItem){
              store.eachItem(function(childResource){
                if (!resource.hasOwnProperty('taskId')) {
                  assignments = assignments.concat(gantt.getResourceAssignments(childResource.id));
                }
              }, resourceId)
            }
          }
          return assignments;
        }
        // 点击修改
        gantt.$clickModify = function (taskId, type, value) {
          let type1 = 0
          if (value === '指派') {
            type1 = 1
          } else if (value === '预计工时') {
            type1 = 2
          } else if (value === '工时相关') {
            type1 = 3
          } /*else if (value === '认定工时') {
            type1 = 4
          }*/
          that.$emit('xiugaiTime', taskId, type1)
          let w = document.querySelector('.modify-select-box' + taskId)
          let w1 = w.getElementsByTagName('option')
          w1[0].selected = true
        }
        let resourceConfig = {
          scale_height: 30,
          scales: [
            {unit: "day", step: 1, date: "%M%d号"}
          ],
          columns: [
            {
              name: "职位/姓名/任务", label: "职位/姓名/任务", width:200, tree:true, template: function (resource) {
                return resource.text;
              }, resize: true
            },
            {
              name: "总工时", label: "总工时", align:"center",template: function (resource) {
                let totalDuration = 0;
                if (resource.hasOwnProperty('taskId')) {
                  gantt.getResourceAssignments(resource.id, resource.taskId).forEach(function(a){
                    totalDuration += a.value * a.duration;
                  });
                } else {
                  getResourceAssignments(resource.id).forEach(function (assignment) {
                    totalDuration += Number(assignment.value) * assignment.duration;
                  });
                }
                return (totalDuration || 0) + "h";
              }
            },
            { name: "buttons", label: '修改工时', width: 15, align:"center", template: function (task) {
                let a = ''
                if (task.taskId) {
                    // a = '<i class="el-icon-thumb" data-action="xiugai" style="margin-right: 2px; cursor: pointer" onclick="gantt.$clickModify('+ "'"  + task.taskId+ "'" + ', 1)"></i>' + a
                    // a = '<i class="el-icon-s-tools" data-action="xiugai" style="margin-right: 2px; cursor: pointer" onclick="gantt.$clickModify('+ "'"  + task.taskId+ "'" + ', 2)"></i>' + a
                  a += '<select class="modify-select-box modify-select-box' + task.taskId +'" onchange="gantt.$clickModify('+ "'"  + task.taskId+ "'" + ', 1, this.options[this.options.selectedIndex].label)">' +
                      '<option label="操作"></option>' +
                      '<option label="指派"></option>' +
                      '<option label="预计工时"></option>' +
                      '<option label="工时相关"></option>' +
                      // '<option label="认定工时"></option>' +
                      '</select>'
                }
                return a
              }}

          ]
        };
        let resourceTemplates = {
          grid_row_class: function(start, end, resource){
            let css = [];
            if(gantt.$resourcesStore.hasChild(resource.id)){
              css.push("folder_row");
              css.push("group_row");
            }
            // if(shouldHighlightResource(resource)){
            //   css.push("highlighted_resource");
            // }
            return css.join(" ");
          },
          task_row_class: function(start, end, resource){
            let css = [];
            // if(shouldHighlightResource(resource)){
            //   css.push("highlighted_resource");
            // }
            if(gantt.$resourcesStore.hasChild(resource.id)){
              css.push("group_row");
            }

            return css.join(" ");

          }
        };
        gantt.$resourcesStore = gantt.createDatastore({
          name: gantt.config.resource_store,
          type: "treeDatastore",
          initItem: function (item) {
            item.parent = item.parent || gantt.config.root_id;
            item[gantt.config.resource_property] = item.parent;
            // item.open = true;
            return item;
          }
        });
        gantt.config.layout = {
          css: "gantt_container",
          rows: [
            {
              gravity: 2,
              cols: [
                {view: "grid", group:"grids", scrollY: "scrollVer"},
                {resizer: true, width: 1},
                {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
                {view: "scrollbar", id: "scrollVer", group:"vertical"}
              ]
            },
            { resizer: true, width: 1, next: "resources"},
            {
              height: 35,
              cols: [
                { html: "", group:"grids"},
                { resizer: true, width: 1},
                { html: "<input style='padding-left: 10px; height: 25px' value='输入姓名、任务、组别'></input>" +
                      "<button style='height: 30px; width: 100px' class='resourcesHeadTable'>查询</button>",
                  css:"resource-controls"
                }
              ]
            },

            {
              gravity:1,
              id: "resources",
              config: resourceConfig,
              templates: resourceTemplates,
              cols: [
                { view: "resourceGrid", group:"grids", scrollY: "resourceVScroll" },
                { resizer: true, width: 1},
                { view: "resourceTimeline", scrollX: "scrollHor", scrollY: "resourceVScroll"},
                { view: "scrollbar", id: "resourceVScroll", group:"vertical"}
              ]
            },
            {view: "scrollbar", id: "scrollHor"}
          ]
        };
        let weekScaleTemplate = function (date) {
          let dateToStr = gantt.date.date_to_str("%Y年%M%d");
          let weekNum = gantt.date.date_to_str("(%W周)");
          let endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
          return dateToStr(date) + " - " + dateToStr(endDate) + " " + weekNum(date);
        };
        let dayScaleTemplate = function (date) {
          let dateToStr = gantt.date.date_to_str("%d号(%l)");
          return dateToStr(date).replace('星期', '')
        };
        gantt.config.scale_height = 60
        gantt.config.scales = [
          {unit: "week", step: 1, format: weekScaleTemplate},
          {unit: "day", step: 1, format: dayScaleTemplate}
        ];
        gantt.config.columns = [
          {
            name: "overdue", label: "", width: 20, template: function (obj) {
              if (obj.deadline && obj.type !== 'milestone') {
                let deadline = obj.deadline.valueOf();
                let w = that.tableData.find(it => it.Id === obj.id)
                if (w.Stage === 8 || w.Stage === 9 || w.Stage === 10) {
                  return;
                }
                if (w.Level >= 100) {
                  return '<div class="overdue-indicator" style="color: red" title="加急任务">急</div>';
                }
                if (deadline && new Date().getTime() > obj.end_date && obj.progress !== 1) {
                  if (w.Tasktimes) {
                    let ww = w.Tasktimes.some(it => it.Cognizanceuserid === '0')
                    if (ww) {
                      return '<div class="overdue-indicator" style="color: #00FF00" title="有待认定记录"><i class="el-icon-chat-square"></i></div>';
                    }
                  }
                  return '<div class="overdue-indicator" style="color: red" title="延期"><i class="el-icon-warning"></i></div>';
                }
              }
              return '<div></div>';
            }
          },
          {name:"text", resize:true, label:"任务名", tree:true, width: 500, template: function (task) {
              return '<div class="overdue-indicator" title="'+ task.text +'">'+ task.text +'</div>';
            } },
          // {name:"start_date", label:"开始时间", align:"center", width: 100 },
          {name:"duration", resize:true, label:"完成/总数|工时", width: 100, align:"center", template: function (task) {
              if (task.parent === '0' && task.type !== 'milestone') {
                let t = that.tableData.filter(it => it.Parenttaskid === task.id)
                let a = t.filter(it => it.Progress.toString() === '100' && it.Status.toString() === '3')
                return `${a.length}/${t.length}`
              } else {
                if (task.parent !== '0') {
                  gantt.refreshTask(task.parent)
                }
                return task.duration
              }
            } },
          {name:"Stage", resize:true, label:"阶段", align:"center", width: 80, template: function (task) {
            let famd = that.tableData.find(it => it.Id === task.id)
            return that.getCode((famd.Stage || '').toString(), 'TASK_STAGE')
          }},
          {name:"status", resize:true, label:"状态", align:"center", width: 80, template: function (task) {
            if (task.status.toString() !== '0') {
              return that.taskStatus[task.status - 1]
            }
            return '未开始'
              // if (task.status.toString() !== '0') {
              //   if (task.parent === '0' && task.type !== 'milestone') {
              //     let t = that.tableData.filter(it => it.Parenttaskid === task.id)
              //     if (t.length !== 0) {
              //       let a = t.filter(it => it.Status.toString() === '1')
              //       let b = t.filter(it => it.Progress.toString() === '100' && it.Status.toString() === '3')
              //       if (t.length === a.length) {
              //         return that.taskStatus[0]
              //       }
              //       if (t.length === b.length) {
              //         return that.taskStatus[2]
              //       }
              //       if (t.length !== b.length) {
              //         return that.taskStatus[1]
              //       }
              //     }
              //     return that.taskStatus[0]
              //   } else {
              //     if (task.status.toString() === '4') return that.statusType(task.status)
              //     if (task.progress === 1) {
              //       return that.statusType('3')
              //     } else if (task.progress === 0) {
              //       let t1 = that.tableData.filter(it => it.Id === task.id)
              //       if (t1.length > 0) {
              //         if (t1[0].Actualstarttime === 0) {
              //           t1[0].Status = '1'
              //           return that.statusType('1')
              //         } else {
              //           t1[0].Status = '2'
              //           return that.statusType('2')
              //         }
              //       }
              //     } else {
              //       return that.statusType('2')
              //     }
              //   }
              // }
            }
          },
          {name:"Level", resize:true,   label:"优先级",   align:"center", template: (task) => {
              let t = that.tableData.find(it => it.Id === task.id)
              if (t) {
                return t.Level || ''
              }
              return ''
            } },
          {name:"Acceptrealname", resize:true,   label:"负责人",   align:"center", template: (task) => {
              let t = that.tableData.filter(it => it.Id === task.id)
              if (t.length > 0) {
                return t[0].Acceptrealname
              }
            } },
          {name: "buttons",label: '<div class="gantt_grid_head_cell gantt_grid_head_add" onclick="gantt.createTask()"></div>'
            ,width: 75,align:"center",
            template: function (task) {
              let childTasks = gantt.getTaskBy(it => it.parent === task.id);
              let a = ''
              if (childTasks.length > 0 && task.type !== 'milestone') {
                a = '<i class="el-icon-plus" data-action="add" style="margin-right: 2px; cursor: pointer"></i>' + a
              }
              // if (childTasks.length === 0 && task.type !== 'milestone') {
              //   a = '<i class="el-icon-minus" data-action="deleteTask" style="margin-right: 2px; cursor: pointer"></i>' + a
              // }
              // if (task.parent !== '0' && task.type !== 'milestone') {
              //   a = '<i class="el-icon-minus" data-action="delete" style="margin-right: 2px; cursor: pointer"></i>' + a
              // }
              return a
            }}
        ];
        gantt.attachEvent("onRowDragStart", function(id, target, e) {
          return true;
        });
        gantt.attachEvent("onBeforeRowDragEnd", function (id, parent, tindex){
          let task = gantt.getTask(id);

          if (task.parent !== parent) {
            that.warning("挂能挂组拖拽数据，请使用切换分组")
            return false
          }
          that.$nextTick(() => {
            projectTaskApi.getModifyOrder({
              id: task.id,
              Ptaskid: parent,
              Neworders: task.$local_index,
              Oldorders: task.remoteOrder
            })
            task.remoteOrder = task.$local_index
          })
          return true
        });
        gantt.attachEvent("onTaskClick", function(id, e){
          var button = e.target.closest("[data-action]")
          if(button){
            var action = button.getAttribute("data-action");
            switch (action) {
              case "add":
                // gantt.createTask(null, id);
                let b = that.tableData.filter(it => it.Id === id)
                if (b.length > 0) {
                  that.$emit('addDdlVisible', b[0], 'add')
                }
                break;
              case "edit":
                gantt.showLightbox(id);
                break;
              case "deleteTask":
                gantt.confirm({
                  title: gantt.locale.labels.confirm_deleting_title,
                  text: '是否删除该任务',
                  callback: function (res) {
                    if (res)
                      gantt.deleteTask(id);
                  }
                });
                break;
            }
            return false;

          }
          return true;
        });
        // gantt.config.drag_project = true;
        // 双击
        // gantt.config.autoscroll = true;
        gantt.attachEvent('onTaskDblClick', (...a) => {
          let Id = a[0]
          let b = that.tableData // this.flatArray(that.tableData, [])
          b = b.filter(it => it.Id === Id)
          that.addData = b[0]
          let task = gantt.getTask(Id)
          if (task.type === 'milestone') {
            this.$emit('milestoneVisible', this.addData)
          } else {
            if (task.parent === '0') {
              that.$emit('modifyTask', b[0])
            } else {
              this.$emit('addDdlVisible', this.addData, 'dbClick')
            }
          }
        })
        gantt.attachEvent("onContextMenu", function (taskId, linkId, event) {
          let x = event.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
              y = event.clientY+document.body.scrollTop+document.documentElement.scrollTop;
          if (taskId) {
            if (gantt.getState().fullscreen) {
              that.left = x
              that.top = y
            } else {
              that.left = x - 10
              that.top = y - 145
            }
            that.rightShowBtn(taskId)
            return false;
          }
          return true;
        });
        // 头部 + 号触发
        gantt.attachEvent('onTaskCreated', (...a) => {
          that.addData = {
            Parenttaskid: a[0].parent
          }
          let w = this.tableData // this.flatArray(this.tableData, [])
          let b = w.filter(it => it.Id === a[0].parent)
          if (b.length > 0) {
            if (b[0].Classify === '3') {
              return this.warning('里程碑不可添加子任务')
            }
          }
          this.$emit('addVisible')
        })
        // 拖动完成并释放鼠标
        this.TaskDragFun()
        this.taskLink()
        gantt.plugins({
          fullscreen: true
        });
        gantt.addTaskLayer(function draw_deadline(task) {
          if (task.deadline) {
            var el = document.createElement('div');
            el.className = 'deadline';
            var sizes = gantt.getTaskPosition(task, task.deadline);

            el.style.left = sizes.left + 'px';
            el.style.top = sizes.top + 'px';

            el.setAttribute('title', gantt.templates.task_date(task.deadline));
            return el;
          }
          return false;
        });
        gantt.templates.task_class = function (start, end, task) {
          if (task.deadline && new Date().getTime() > end.getTime()) {
            return 'overdue';
          }
        };
        gantt.templates.rightside_text = function (start, end, task) {
          if (task.deadline && task.type !== 'milestone') {
            if (new Date().getTime() > end.getTime() && task.progress !== 1) {
              let overdue = Math.ceil(Math.abs((new Date().getTime() - end.getTime()) / (24 * 60 * 60 * 1000)));
              let text = "<b>延期: " + overdue + " 天</b>";
              return text;
            }
          }
        };
        let data = this.tableData
        // 人员资源图
        gantt.templates.resource_cell_value = function(start_date, end_date, resource, tasks, assignments){
          if (resource.hasOwnProperty('taskId')) {
            if(start_date < tasks[0].end_date && end_date > tasks[0].start_date){
              for (let i = 0; i < assignments.length; i++){
                let a = assignments[i];
                let w = data.find(it => it.Id === resource.taskId)
                let showTime = ['-', '-', '-']
                if (w.Tasktime) {
                  showTime[0] = parseInt((w.Tasktime).toString())
                }
                let tim = (w.Tasktimes || []).filter(it => {
                  let ts = it.Started.toString().length === 10 ? it.Started * 1000 : it.Started
                  let te = it.Ended.toString().length === 10 ? it.Ended * 1000 : it.Ended
                  let s = new Date(start_date).valueOf() <= new Date(ts).valueOf()
                  let e = new Date(end_date).valueOf() >= new Date(te).valueOf()
                  return s && e
                })
                if (tim && tim.length > 0) {
                  showTime[1] = tim.reduce((totle, it) => {
                    let a = Number(it.Tasktime)
                    if (isNaN(a)) a = 0
                    return totle += a
                  }, 0)
                  showTime[2] = tim.reduce((totle, it) => {
                    let a = Number(it.Cognizancetasktime)
                    if (isNaN(a)) a = 0
                    return totle += a
                  }, 0)
                }
                return "<div>" + showTime.join('/') + "</div>"
                // return "<div contenteditable data-assignment-cell data-assignment-id='"+a.id+"'"+
                //     " data-row-id='"+resource.id+"'"+
                //     " data-task='"+resource.taskId+"'"+
                //     " data-start-date='"+gantt.templates.format_date(start_date)+"'"+
                //     " data-end-date='"+gantt.templates.format_date(end_date)+"'>" + showTime.join('/') + "</div>"
              }
              return "<div contenteditable data-assignment-cell data-empty "+
                  " data-row-id='"+resource.id+"'"+
                  " data-resource-id='"+resource.user_id+"'"+
                  " data-task='"+resource.taskId+"'"+
                  " data-start-date='"+gantt.templates.format_date(start_date)+"'"+
                  "'  data-end-date='"+gantt.templates.format_date(end_date)+"'>-</div>";
            }
          } else {
            let sum = assignments.reduce(function(total, assignment){
              if (assignment.value) {
                return total + Number(assignment.value);
              }
              return total
            }, 0);

            if(sum % 1){
              sum = Math.round(sum * 10)/10;
            }

            if(sum){
              return "<div>" + sum + "</div>";
            }
            return "";
          }
        };
        gantt.attachEvent("onGanttReady", function(){
          gantt.event(gantt.$container, "focusout", function(e){

          });
          let w = document.getElementsByClassName('resourcesHeadTable')[0]
          let inputs = document.getElementsByClassName('resource-controls')[0]
          let ww = inputs.getElementsByTagName('input')
          Array.from(ww).forEach((it, index) => {
            it.addEventListener('focus', () => {
              if (index === 0 && it.value === '输入姓名、任务、组别') {
                it.value = ''
              }
            })
            it.addEventListener('blur', () => {
              if (index === 0 && it.value === '') {
                it.value = '输入姓名、任务、组别'
              }
            })
          })
          w.addEventListener('click', () => {
            let txt1 = ww[0].value
            if (txt1 === '输入姓名、任务、组别' || txt1 === '') {
              that.getTaskName('')
            } else {
              that.getTaskName(txt1)
            }
          })
        })
        // 全屏
        gantt.attachEvent("onExpand", function (){
          that.closeContextMenu()
        });
        // 退出
        gantt.attachEvent("onCollapse", function (){
          that.closeContextMenu()
        });
        gantt.init("gantt_here")
      })
    },
    // 获取任务名称
    getTaskName (txt2) {
      // let store = gantt.$resourcesStore;
      // console.log(store)
      let w1 = hanlderGroup(this.tableData).w1
      let w3 = w1
      if (txt2 !== '') {
        let w = w1.filter(it => {
          return /*!w1.some(it1 => it1.parent === it.id) &&*/ it.text.indexOf(txt2) >= 0
        })
        w3 = this.searchParen(w, w1)
        let w4 = this.searchChrld(w, w1)
        w3.push(...w4)
        if (w3.length === 0) {
          return this.$message({ type: 'warning', message: '无查询结果' })
        } else {
        }
      }
      gantt.$resourcesStore.clearAll()
      gantt.$resourcesStore.parse(w3)
      gantt.render();

    },
    // 搜父
    searchParen (w, data) {
      let w2 = []
      w.forEach(it => {
        w2.push(it)
        let w1 = data.find(it1 => it1.id === it.parent)
        if (w1) {
          let w4 = this.searchParen([w1], data)
          w2.push(...w4)
        }
      })
      return w2
    },
    // 搜子
    searchChrld (w, data) {
      let w1 = []
      w.forEach(it => {
        w1.push(it)
        let w2 = data.filter(it1 => it1.parent === it.id)
        let w3 = this.searchChrld(w2, data)
        w1.push(...w3)
      })
      return w1
    },
    // 任务类型
    gttType (it, b) {
      if (it.Parenttaskid === '0' && it.Classify !== '3') {
        return gantt.config.types.project
      }
      if (it.Classify === '3') return gantt.config.types.milestone
      return gantt.config.types.task
    },
    // 拖动触发
    TaskDragFun () {
      if (!this.TaskDragThrottle) this.TaskDragThrottle = new Date().getTime()
      let lthrottleSize = 500
      gantt.attachEvent('onAfterTaskDrag', (...a) => {
        console.log('onAfterTaskDrag')
        this.closeContextMenu()
        let t = new Date().getTime()
        if (t - this.TaskDragThrottle > lthrottleSize) {
          this.TaskDragThrottle = new Date().getTime()
          this.updateTaskDrag(a[0])
        }
      })
    },

    // 链接触发
    taskLink () {
      if (!this.linkUpdateThrottle) this.linkUpdateThrottle = new Date().getTime()
      let lthrottleSize = 500
      // 新增链接
      gantt.attachEvent('onAfterLinkAdd', (...a) => {
        this.closeContextMenu()
        let t = new Date().getTime()
        if (t - this.linkUpdateThrottle > lthrottleSize) {
          this.linkUpdateThrottle = new Date().getTime()
          this.updateRelated(a[0], a[1], 'c')
        }
      })
      // 删除链接
      gantt.attachEvent('onAfterLinkDelete', (...a) => {
        this.closeContextMenu()
        let t = new Date().getTime()
        if (t - this.linkUpdateThrottle > lthrottleSize) {
          this.linkUpdateThrottle = new Date().getTime()
          this.updateRelated(a[0], a[1], 'd')
        }
      })
      // 更新链接
      gantt.attachEvent('onAfterLinkUpdate', (...a) => {
        this.closeContextMenu()
        let t = new Date().getTime()
        if (t - this.linkUpdateThrottle > lthrottleSize) {
          this.linkUpdateThrottle = new Date().getTime()
          this.updateRelated(a[0], a[1], 'u')
        }
      })
    },
    statusType (status) {
      if (status.toString() !== '0') return this.taskStatus[status - 1]
    }
  }
}
</script>

<style scoped>
#gantt_here >>> .curshubiao:hover {
  cursor: pointer;
}
#gantt_here >>> .nested_task .gantt_add{
  display: none !important;
}
.contextmenu {
  width: 100px;
  margin: 0;
  border: 1px solid #ccc;
  background: #fff;
  z-index: 9000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.2);
}
.contextmenu li {
  margin: 0;
  padding: 0px 22px;

}
.contextmenu li:hover {
  background: #f2f2f2;
  cursor: pointer;
}
.contextmenu li button{
  color: #2c3e50;
}
#gantt_here{
  z-index: 20 !important;
}
.divider {
  margin: 0;
}
#gantt_here >>> .weekend {
  background: #f4f7f4 !important;
}
#gantt_here >>> .modify-select-box {
  padding: 3px 10px;
  border: none;
  /* background-color: rgb(246, 171, 138); */
  appearance: none;
  -moz-appearance: none;
  -webkit-appearance: none;
  text-align: center;
  text-align-last: center;
}
#gantt_here >>> .resource-controls .gantt_layout_content {
  display: flex;
  align-items: center;
}
</style>
